package cn.vcjf.weapp.api.payment.qfwxpay.service.QfApi;

import cn.vcjf.weapp.api.payment.qfwxpay.service.AbstractQfWxPayAuth;
import cn.vcjf.weapp.common.util.httpUtils.HttpClientUtils;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 测试微信授权类
 *
 * @author jauyang
 */
public class QfPayAuthUtil {

	private static String ACCESS_URL = "https://openapi.qfpay.com/tool/v1/get_weixin_openid?code=";

	private static String GET_OPENID_URL = "https://openapi.qfpay.com/tool/v1/get_weixin_oauth_code?app_code=";

	/**
	 *
	 */
	public static String getCode(HttpServletRequest request, HttpServletResponse response, String appCode,String mchid,String key,  String redirectUrl) throws IOException {
		if (request.getParameter("code") == null) {
			SortedMap<String, String> params = new TreeMap<>();
			params.put("app_code", appCode);
			params.put("mchid", mchid);
			params.put("redirect_uri", redirectUrl);
			String sign = HttpClientUtils.getSign(params,key);

			redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
			String redUrl = GET_OPENID_URL + appCode + "&redirect_uri=" + redirectUrl +"&mchid=" + mchid + "&sign=" + sign;
			System.out.println(redUrl);
			response.sendRedirect(redUrl);
		} else {
			return getOpenId(request, response, appCode, mchid,key);
		}
		return null;
	}

	/**
	 * 获取微信授权的openid
	 */
	public static String getOpenId(HttpServletRequest request, HttpServletResponse response, String appCode,String mchid,String key) {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			String code = request.getParameter("code");
			if (StringUtils.isEmpty(code)) {
				return null;
			}
			String openId = "";
			String requestUrlString = ACCESS_URL+code+"&mchid="+mchid;

			SortedMap<String, String> params = new TreeMap<>();
			params.put("code", code);
			params.put("mchid", mchid);

			Map<String, String> header = new HashMap<>();
			header.put("X-QF-APPCODE", AbstractQfWxPayAuth.APP_CODE);
			header.put("X-QF-SIGN",HttpClientUtils.getSign(params,key));

			String result = HttpClientUtils.doGet(requestUrlString,null,header);

			if (StringUtils.isNotBlank(result) ) {
				JSONObject jsonObject = JSONObject.parseObject(result);
				System.out.println(jsonObject);
				openId = jsonObject.getString("openid");
				//oYCFB0opzyfpg-BmTVTCcZchAE2k
			}
			return StringUtils.isBlank(openId) ? "" : openId;
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
}
